#include "state_machine.h"
 
 
/**
 * 初始化状态机
 * 
 * @param machine   指向 StateMachine 结构体的指针
 * @param rules     状态转换规则数组
 * @param ruleCount 转换规则的数量
 * @param context   指向状态机上下文数据的指针
 * @param handlers  状态处理函数数组
 */
void state_machine_init(StateMachine *machine, TransitionRule *rules, size_t ruleCount, void *context, StateHandler *handlers) {
    // 设置当前状态为第一个转换规则的当前状态
    machine->currentState = rules[0].currentState;
    
    // 存储转换规则数组、规则数量和上下文数据
    machine->rules = rules;
    machine->ruleCount = ruleCount;
    machine->context = context;
 
    // 将状态处理函数数组初始化为空
    for (size_t i = 0; i < STATE_MAX; i++) {
        machine->handlers[i] = NULL;
    }
 
    // 根据规则的当前状态，从处理函数数组中获取对应的处理函数并存储到状态处理函数数组中
    for (size_t i = 0; i < ruleCount; i++) {
        machine->handlers[machine->rules[i].currentState] = handlers[machine->rules[i].currentState];
    }
}
 
 
 
/* 执行状态机处理 */
void state_machine_handle_event(StateMachine *machine, Event event) {
    for (size_t i = 0; i < machine->ruleCount; ++i) {
        /* 查找匹配的状态转换规则 */
        if (machine->currentState == machine->rules[i].currentState && event == machine->rules[i].event) {
            /* 检查条件判断 */
            if (machine->rules[i].condition(machine->context, event)) {
                /* 执行动作函数 */
                if (machine->rules[i].action != NULL) {
                    machine->rules[i].action(machine->context, event);
                }
 
                /* 更新当前状态 */
                machine->currentState = machine->rules[i].nextState;
 
                /* 调用对应状态的处理函数 */
                if (machine->handlers[machine->currentState] != NULL) {
                    machine->handlers[machine->currentState](machine->context, event);
                }
                break;
            } else {
                /* 处理条件不满足的情况 */
                // TODO: 错误处理代码
                break;
            }
        }
    }
}
 
 
 
/* 获取当前状态 */
State state_machine_get_current_state(StateMachine *machine) {
    return machine->currentState;
}